<template>
  <el-dialog
    :title="!dataForm.id ? '新增' : '修改'"
    :close-on-click-modal="false"
    v-loading="loading"
    element-loading-text="正在上传中。。。"
    :visible.sync="visible">
    <el-form :model="dataForm" :rules="dataRule" ref="dataForm"
             label-width="80px">
      <el-form-item label="镜像名称" prop="name">
        <el-input v-model="dataForm.name" placeholder="镜像名称"></el-input>
      </el-form-item>
      <el-form-item label="镜像描述" prop="description">
        <el-input v-model="dataForm.description" placeholder="镜像描述"></el-input>
      </el-form-item>
      <el-form-item label="文件" prop="file" ref="uploadElement" v-show="!dataForm.id">
        <el-upload
          class="upload-demo"
          ref="upload"
          :on-preview="handlePreview"
          :before-upload="beforeAvatarUpload"
          :on-remove="handleRemove"
          :file-list="fileList"
          multiple
          :limit="1"
          :auto-upload='false'
          :on-success='handleSuccess'
          :on-change="imageChange"
          :action='uploadUrl'
          :data="dataForm"
          name="file">
          <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
        </el-upload>
      </el-form-item>
      <el-form-item label="可见性" prop="isPublic">
        <el-radio-group v-model="dataForm.isPublic">
          <el-radio-button label="1">公有</el-radio-button>
          <el-radio-button label="0">私有</el-radio-button>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="submitUpload(dataForm.id)">确定</el-button>
    </span>
  </el-dialog>


</template>

<script>
    /* eslint-disable quotes,standard/object-curly-even-spacing */

    import _ from "lodash";

    export default {
        data() {
            return {
                loading: false,
                visible: false,
                haspic: false,
                images: [],// 图片存储
                fileList: [],
                uploadUrl: '',
                dataForm: {
                    id: 0,
                    name: '',
                    description: '',
                    isPublic: '1',
                    file: ''
                },
                dataRule: {
                    name: [
                        {required: true, message: '镜像名称不能为空', trigger: 'blur'}
                    ],
                    file: [
                        {required: true, message: '请选择镜像', trigger: 'blur'}
                    ],
                    isPublic: [
                        {required: true, message: '选择可见性', trigger: 'blur'}
                    ]
                }
            }
        },
        methods: {
            init(id) {

                this.dataForm.id = id || 0
                this.visible = true
              this.loading = false
                this.uploadUrl = this.$http.adornHardWareUrl(`/generator/image/upload?token=${this.$cookie.get('token')}`)
                //console.log(this.uploadUrl)
                this.$nextTick(() => {
                    this.$refs['dataForm'].resetFields()
                    if (this.dataForm.id) {
                        this.$http({
                            url: this.$http.adornHardWareUrl(`/generator/image/info/${this.dataForm.id}`),
                            method: 'get',
                            params: this.$http.adornParams()
                        }).then(({data}) => {
                            if (data && data.code === 0) {
                                this.dataForm.name = data.image.name
                                this.dataForm.description = data.image.description
                                this.dataForm.url = data.image.url
                            }
                        })
                    }
                })
            },
            // 表单提交
            dataFormSubmit() {
                this.$refs['dataForm'].validate((valid) => {
                    if (valid) {
                        this.$http({
                            url: this.$http.adornHardWareUrl(`/generator/image/update`),
                            method: 'post',
                            data: this.$http.adornData({
                                'id': this.dataForm.id,
                                'name': this.dataForm.name,
                                'description': this.dataForm.description,
                                'isPublic': this.dataForm.isPublic
                            })
                        }).then(({data}) => {
                          if(data.code === 500){
                            this.$message.error(data.msg)
                            // this.visible = false
                            // this.loading = false
                          }
                            else if (data && data.code === 0) {
                                this.$message({
                                    message: '操作成功',
                                    type: 'success',
                                    duration: 1500,
                                    onClose: () => {
                                        this.visible = false
                                        this.$emit('refreshDataList')
                                    }
                                })
                            } else {
                                this.$message.error(data.msg)
                                // this.visible = false
                                // this.loading = false
                            }
                            this.visible = false
                            this.loading = false
                        }).catch(() => {
                            this.visible = false
                            this.loading = false
                        })
                    }
                })
            },
            submitUpload(id) {
                if (id) {
                    this.dataFormSubmit()
                } else {
                    if (this.haspic) {
                        _.unset(this.dataRule, ["file"])
                        this.$refs['dataForm'].validate((valid) => {
                            if (valid) {
                                this.loading = true
                                this.$refs.upload.submit()
                            }
                        })
                    } else {
                        // 向rules提价一条对图片的验证。
                        _.set(this.dataRule, "file", {required: true, message: "请选择镜像", trigger: "blur"})
                        this.$refs['dataForm'].validate(valid => {
                            if (valid) {
                                console.log("说明镜像没有提交")
                              this.loading=false;
                            } else {
                                console.log("error submit!!")
                              this.loading=false;
                                return false
                            }
                        })
                    }
                }
            },
            beforeAvatarUpload(file) {

                let fileName = file.name.lastIndexOf(".");//取到文件名开始到最后一个点的长度
                let fileNameLength = file.name.length;//取到文件名长度
                let fileFormat = file.name.substring(fileName + 1, fileNameLength);//截
                // console.log(fileFormat)
                // iso/qcow2/img
                if (fileFormat.toLowerCase() === 'iso' || fileFormat.toLowerCase() === 'qcow2' || fileFormat.toLowerCase() === 'img') {
                    // this.$refs.upload.submit();
                } else {
                    this.$message({
                        message:"支持(iso/qcow2/img)镜像文件格式",
                    })
                    this.loading=false;
                    return false;
                }

            },
            imageChange(file, fileList, name) {
                this.images["file"] = fileList;
                this.haspic = true;
                // 如果上传了就不显示提示图片警告
                if (typeof this.images.file != "undefined") {
                    if (this.images.file.length > 0) {
                        this.$refs["uploadElement"].clearValidate();
                    }
                }
            },
            handleRemove(file, fileList) {
                // 如果images为空了说明并没有提交图片所以需要显示警告
                if (typeof this.images.file != "undefined") {
                    if (this.images.file.length > 0) {
                        this.$refs["uploadElement"].clearValidate();
                    } else {
                        this.$refs["uploadElement"].validate();
                        this.haspic = false;
                    }
                }
            },
            handlePreview(file) {
            },
            handleSuccess(res, file, fileList) {
                if (res.code === 0) {
                    this.$message({
                        message: '操作成功',
                        type: 'success',
                        duration: 1500,
                        onClose: () => {
                            this.visible = false
                            this.loading = false
                            this.haspic = false
                            this.fileList = []
                            this.$emit('refreshDataList')
                            this.$refs.upload.clearFiles()
                        }
                    })
                }else if(res.code === 500){
                  this.$message({
                    message: res.msg,
                    type: 'error',
                    duration: 1500,
                    onClose: () => {
                      this.visible = false
                      this.loading = false
                      this.haspic = false
                    }
                  })
                } else {
                    this.$message({
                        message: res.msg,
                        type: 'error'
                    })
                }
            }
        }
    }
</script>
